// 统一样式抽离的echart组件
import React, { useRef, useEffect } from 'react';
import * as echarts from 'echarts';
import { getCssVariableValue } from '@/utils/utils';
import { useThemeChange } from '@/hooks/useThemeChange';

interface ReportChartProps {
  xAxisData?: string[] | number[];
  yAxisName?: string;
  yAxis?: echarts.YAXisComponentOption | echarts.XAXisComponentOption[];
  xAxis?: echarts.XAXisComponentOption | echarts.XAXisComponentOption[]; // 支持单个或多个xAxis
  series?: echarts.SeriesOption[];
  dataZoom?: boolean;
  width?: number | string;
  height?: number | string;
  className?: string;
  style?: React.CSSProperties;
  loading?: boolean;
  option?: echarts.EChartsOption; // 允许完全自定义配置
  theme?: string;
  onChartReady?: (chart: echarts.ECharts) => void;
  onClick?: (params: any) => void;
  echartTitle?: echarts.TitleComponentOption;
}

const Chart: React.FC<ReportChartProps> = ({
  xAxisData,
  yAxisName,
  yAxis,
  xAxis,
  series,
  dataZoom = false,
  width = '100%',
  height = 400,
  className,
  style,
  loading = false,
  option,
  echartTitle,
  onChartReady,
  onClick,
}) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<echarts.ECharts | null>(null);
  const { theme } = useThemeChange();
  const getChartOption = (): echarts.EChartsOption => ({
    animation: false,
    title: {
      top: 0,
      padding: 0,
      ...(echartTitle || {}),
      left: '10%',
    },

    color: [
      '#588AEF',
      '#E86452',
      '#3AD7CE',
      '#B382F0',
      '#5E92F6',
      '#F5BE15',
      '#FB6E77',
      '#ED8139',
      '#00BF8F',
    ], // 自定义颜色方案
    textStyle: {
      fontFamily: 'Microsoft YaHei, SimHei, sans-serif',
    },
    grid: {
      top: '10%',
      left: '4%',
      right: '4%',
      bottom: '10%',
      containLabel: true,
    },
    legend: {
      right: 'center',
      top: 'bottom',
      padding: [16, 0, 0, 0],
      itemGap: 20,
      itemWidth: 15,
      itemHeight: 8,
      textStyle: {
        color: getCssVariableValue('--chart-legend-color'),
      },
      show: true,
      inactiveColor: '#545454',
      inactiveBorderColor: '#545454',
      inactiveBorderWidth: 'inherit',
    },

    tooltip: {
      trigger: 'axis',
      backgroundColor: '#161A1D',
      textStyle: {
        fontSize: 14,
        lineHeight: 14,
        color: '#A7A8A9',
        align: 'left',
      },
      borderWidth: 0,
      axisPointer: {
        type: 'line',
        lineStyle: { width: 1, color: '#4E5154', type: 'solid' },
      },
    },
    xAxis: Array.isArray(xAxis)
      ? xAxis
      : {
          type: 'category',
          data: xAxisData || [],
          axisPointer: {
            type: 'line',
            lineStyle: {
              type: 'solid',
              color: getCssVariableValue('--chart-x-line'),
            },
          },
          axisLine: {
            show: true,
            onZero: false,
            lineStyle: {
              type: 'solid',
              color: getCssVariableValue('--chart-x-line'),
            },
          },
          axisTick: {
            alignWithLabel: true,
            lineStyle: {
              color: getCssVariableValue('--chart-x-line'),
            },
          },
          axisLabel: {
            color: getCssVariableValue('--chart-font-color'),
          },
          ...(xAxis || {}),
        },
    yAxis: Array.isArray(yAxis)
      ? yAxis
      : {
          type: 'value',
          name: yAxisName,
          nameTextStyle: {
            color: getCssVariableValue('--chart-font-color'),
            align: 'right',
          },
          axisTick: {
            alignWithLabel: true,
            length: 4,
            lineStyle: {
              color: getCssVariableValue('--chart-y-line'),
            },
          },
          axisLabel: {
            color: getCssVariableValue('--chart-font-color'),
            fontSize: 12,
          },
          splitLine: {
            show: true,
            lineStyle: {
              type: 'solid',
              color: getCssVariableValue('--chart-y-line'),
            },
          },
          ...(yAxis || {}),
        },
    ...(dataZoom && {
      dataZoom: {
        type: 'slider',
        start: 0,
        end: 100,
        left: 40,
        right: 10,
        bottom: 30,
        height: 20,
        backgroundColor: getCssVariableValue('--bg-form'),
        borderColor: 'transparent',
        handleStyle: {
          color: getCssVariableValue('--bg-form'),
          borderColor: getCssVariableValue('--bd'),
        },
        brushSelect: false,
        showDetail: false,
      },
    }),
    series: (series || []).map((item: any) => ({
      ...item,
      label: {
        ...(item.label || {}),
        fontSize: 12,
        fontFamily: 'Microsoft YaHei, SimHei, sans-serif',
        formatter: '{b}\n{d}%',
        color: getCssVariableValue('--chart-font-color'),
      },
      type: 'line',
      symbol: 'none',
      emphasis: {
        symbol: 'circle',
        symbolSize: 8,
      },
    })),
  });

  useEffect(() => {
    if (!chartRef.current) return;

    chartInstance.current = echarts.init(chartRef.current);

    // 使用自定义配置或默认配置
    const finalOption = option || getChartOption();
    chartInstance.current.setOption(finalOption);

    // 设置loading状态
    if (loading) {
      chartInstance.current.showLoading();
    } else {
      chartInstance.current.hideLoading();
    }

    // 绑定点击事件
    if (onClick) {
      chartInstance.current.on('click', onClick);
    }

    if (onChartReady) {
      onChartReady(chartInstance.current);
    }

    const handleResize = () => {
      if (chartInstance.current && !chartInstance.current.isDisposed()) {
        chartInstance.current.resize();
      }
    };

    // 监听window resize
    window.addEventListener('resize', handleResize);

    // 使用ResizeObserver监听容器尺寸变化
    let resizeObserver: ResizeObserver | null = null;
    if (chartRef.current) {
      resizeObserver = new ResizeObserver(() => {
        setTimeout(handleResize, 100); // 延迟执行，确保DOM更新完成
      });
      resizeObserver.observe(chartRef.current);
    }

    return () => {
      window.removeEventListener('resize', handleResize);
      if (resizeObserver) {
        resizeObserver.disconnect();
      }
      if (chartInstance.current && !chartInstance.current.isDisposed()) {
        if (onClick) {
          chartInstance.current.off('click', onClick);
        }
        chartInstance.current.dispose();
      }
    };
  }, [xAxisData, yAxisName, series, dataZoom, loading, option, onChartReady]);

  // 更新loading状态
  useEffect(() => {
    if (chartInstance.current) {
      if (loading) {
        chartInstance.current.showLoading();
      } else {
        chartInstance.current.hideLoading();
      }
    }
  }, [loading]);

  useEffect(() => {
    setTimeout(() => {
      // 使用自定义配置或默认配置
      const finalOption = option || getChartOption();
      chartInstance?.current?.setOption(finalOption);
    }, 0);
  }, [theme]);

  return (
    <div
      data-echarts
      ref={chartRef}
      className={className}
      style={{
        width,
        height,
        ...style,
      }}
    />
  );
};

export default Chart;
